package com.cn.travel.web.portal;

import com.alibaba.fastjson.JSONObject;
import com.cn.travel.cms.verifyCode.entity.VerifyCode;
import com.cn.travel.cms.verifyCode.service.IVerifyCodeGen;
import com.cn.travel.cms.verifyCode.service.impl.SimpleCharVerifyCodeGenImpl;
import com.cn.travel.role.user.entity.User;
import com.cn.travel.role.user.service.imp.UserService;
import com.cn.travel.utils.MD5Util;
import com.cn.travel.utils.Tools;
import com.cn.travel.web.base.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Controller
public class UserPortalController extends BaseController {

    @Autowired
    UserService userService;

    private static final Logger LOGGER = LoggerFactory.getLogger(UserPortalController.class);
    String code;

    @GetMapping("/verifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response) {
        IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
        try {
            //设置长宽
            VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
            code = verifyCode.getCode();
            LOGGER.info(code);
            //将VerifyCode绑定session
            request.getSession().setAttribute("VerifyCode", code);
            //设置响应头
            response.setHeader("Pragma", "no-cache");
            //设置响应头
            response.setHeader("Cache-Control", "no-cache");
            //在代理服务器端防止缓冲
            response.setDateHeader("Expires", 0);
            //设置响应内容类型
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
        } catch (IOException e) {
            LOGGER.info("", e);
        }
    }

    @RequestMapping("/userPhoneLoging")
    public ModelAndView userPhoneLoging(String memPhone,String code,
                                        RedirectAttributes redirectAttributes,HttpSession httpSession){

        JSONObject userCode = (JSONObject)httpSession.getAttribute("code");

        System.out.println("memPhone："+memPhone);
        System.out.println("userCode.get(memPhone)："+userCode.get("memPhone"));

        if (memPhone.length() != 11 || memPhone.charAt(0) != '1'){
            System.out.println("手机号格式不符合规范!");
            redirectAttributes.addFlashAttribute("message","手机号格式不符合规范!");
            return new ModelAndView(new RedirectView("/goPhoneLogin"));
        }
        User user = userService.loginByPhone(memPhone);
        if (Tools.isEmpty(user)) {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            userService.saveNPS(uuid, "用户" + memPhone, memPhone, 1);
            user = userService.loginByPhone(memPhone);
        }
        userService.updateDeleteStatus(memPhone);
        if (Tools.isEmpty(code)){
            System.out.println("验证码不能为空!");
            redirectAttributes.addFlashAttribute("message","验证码不能为空!");
            return new ModelAndView(new RedirectView("/goPhoneLogin"));
        }
        if (!(userCode.get("code").equals(code))){
            redirectAttributes.addFlashAttribute("message","验证码不正确!");
            return new ModelAndView(new RedirectView("/goPhoneLogin"));
        }
        if (user.getState() == 1) {
            httpSession.setAttribute("userName",user.getUserName());
            return new ModelAndView(new RedirectView("/userCenter"));
        } else {
            System.out.println("网络连接超时!");
            redirectAttributes.addFlashAttribute("message","网络连接超时!");
            return new ModelAndView(new RedirectView("/goPhoneLogin"));
        }
    }

    @RequestMapping("/userLoging")
    public ModelAndView userLoging(String userName,String password,String CODE,RedirectAttributes redirectAttributes,HttpSession httpSession){
        if(Tools.notEmpty(httpSession.getAttribute("userName"))){
            return new ModelAndView(new RedirectView("/userCenter"));
        }
        if (Tools.isEmpty(userName)){
            redirectAttributes.addFlashAttribute("message","用户名不得为空!");
            return new ModelAndView(new RedirectView("/goLogin"));
        }
        if (Tools.isEmpty(password)){
            redirectAttributes.addFlashAttribute("message","密码不得为空!");
            return new ModelAndView(new RedirectView("/goLogin"));
        }

        String pwdByName = userService.getPwdByName(userName);
        System.out.println("pwdByName："+pwdByName);
        String encryptPwd = MD5Util.encrypt(password);
        System.out.println("encryptPwd："+pwdByName);

        if (!(pwdByName.equals(encryptPwd))){
            redirectAttributes.addFlashAttribute("message","密码不正确!");
            return new ModelAndView(new RedirectView("/goLogin"));
        }
        if (!CODE.equals(code)){
            redirectAttributes.addFlashAttribute("message","验证码错误!");
            return new ModelAndView(new RedirectView("/goLogin"));
        }
        try {
            User user = userService.login(userName, encryptPwd);
            if (Tools.isEmpty(user)){
                redirectAttributes.addFlashAttribute("message","用户名不存在或密码错误!");
                return new ModelAndView(new RedirectView("/goLogin"));
            }else{
                if (user.getState() == 1) {
                    httpSession.setAttribute("userName",userName);
                    return new ModelAndView(new RedirectView("/userCenter"));
                } else {
                    redirectAttributes.addFlashAttribute("message","账户已被注销!");
                    return new ModelAndView(new RedirectView("/goLogin"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ModelAndView(new RedirectView("/goLogin"));
    }

    @RequestMapping("/register")
    public ModelAndView register(){
        ModelAndView mv = this.getModeAndView();
        mv.setViewName("portal/register");
        return mv;
    }

    @RequestMapping("/registering")
    public ModelAndView registering(String userName,String password,String checkPassword,
                                    String linkTel,String name,String icCode,String agree,
                                    HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception{
        User user = new User();
        this.bindValidateRequestEntity(request,user);
        if(Tools.isEmpty(userName)){
            redirectAttributes.addFlashAttribute("message","用户名不得为空!");
            return new ModelAndView(new RedirectView("/register"));
        }
        User u = userService.findByUserName(userName);
        if(!(Tools.isEmpty(u))){
            redirectAttributes.addFlashAttribute("message","用户名已存在!");
            return new ModelAndView(new RedirectView("/register"));
        }
        User entity = userService.findByUserName(userName);
        if (entity != null) {
            redirectAttributes.addFlashAttribute("message","用户名已存在!");
            return new ModelAndView(new RedirectView("/register"));
        }
        if(Tools.isEmpty(password)){
            redirectAttributes.addFlashAttribute("message","密码不得为空!");
            return new ModelAndView(new RedirectView("/register"));
        }
        if(!user.getPassword().equals(checkPassword)){
            redirectAttributes.addFlashAttribute("message","密码与确认密码不一致!");
            return new ModelAndView(new RedirectView("/register"));
        }
        if(Tools.isEmpty(linkTel)){
            redirectAttributes.addFlashAttribute("message","手机号码不得为空!");
            return new ModelAndView(new RedirectView("/register"));
        }
        char first = linkTel.charAt(0);
        System.out.println("手机号码第一位是："+first);
        if(linkTel.length() != 11 || linkTel.charAt(0) != '1'){
            redirectAttributes.addFlashAttribute("message","手机号码格式不正确!");
            return new ModelAndView(new RedirectView("/register"));
        }
        if(Tools.isEmpty(name)){
            redirectAttributes.addFlashAttribute("message","真实姓名不得为空!");
            return new ModelAndView(new RedirectView("/register"));
        }
        if(Tools.isEmpty(icCode)){
            redirectAttributes.addFlashAttribute("message","身份证号不得为空!");
            return new ModelAndView(new RedirectView("/register"));
        }
        if(icCode.length()!=18){
            redirectAttributes.addFlashAttribute("message","身份证号不正确!");
            return new ModelAndView(new RedirectView("/register"));
        }
        if(Tools.isEmpty(agree)){
            redirectAttributes.addFlashAttribute("message","请勾选协议");
            return new ModelAndView(new RedirectView("/register"));
        }

        try {
            user.setId(Tools.getUUID());
            user.setAddTime(new Date());
            user.setUserName(userName);
            user.setPassword(MD5Util.encrypt(password));
            user.setName(name);
            user.setAddUserId(Tools.getUUID());
            user.setLinkTel(linkTel);
            user.setIcCode(icCode);
            user.setState(1);
            userService.save(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        redirectAttributes.addFlashAttribute("message","注册成功，请登陆!");
        return new ModelAndView(new RedirectView("/goLogin"));
    }

    @RequestMapping("/personInfo")
    public ModelAndView personInfo(HttpSession httpSession){
        ModelAndView mv = this.getModeAndView();
        try {
            mv.addObject("entity",userService.findByUserName(httpSession.getAttribute("userName").toString()));
        }catch (Exception e){
            e.printStackTrace();
        }
        mv.setViewName("portal/personalIntro");
        return mv;
    }

    @RequestMapping("/personSave")
    public ModelAndView personSave(HttpServletRequest request, String id,String userName,
                                   String name,String linkTel,String icCode,HttpSession session,
                                   RedirectAttributes redirectAttributes){
        ModelAndView mv = this.getModeAndView();
        User entity = null;
        try{
            if(Tools.notEmpty(id)){
                entity = userService.findById(id);
                entity.setUserName(userName);
                entity.setName(name);
                entity.setLinkTel(linkTel);
                entity.setIcCode(icCode);
            }
            this.bindValidateRequestEntity(request,entity);
            userService.update(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        redirectAttributes.addFlashAttribute("message","信息修改成功，请重新登录!");
        return new ModelAndView(new RedirectView("/goLogout"));
    }

    @RequestMapping("/changePassword")
    public ModelAndView changePassword(HttpSession httpSession){
        ModelAndView mv = this.getModeAndView();
        mv.setViewName("portal/changePassword");
        return mv;
    }

    @RequestMapping("/changePasswordSave")
    public ModelAndView changePasswordSave(String password,String newPassword,String checkPassword,
                                           HttpSession httpSession,RedirectAttributes redirectAttributes) throws Exception {
        ModelAndView mv = this.getModeAndView();
        if(Tools.isEmpty(password)||Tools.isEmpty(newPassword)||Tools.isEmpty(checkPassword)){
            mv.addObject("message","密码输入不能为空！");
            mv.setViewName("portal/changePassword");
            return mv;
        }
        String userName = httpSession.getAttribute("userName").toString();
        User user = userService.findByUserName(userName);
        System.out.println("原密码为："+user.getPassword());
        String passwordMD5 = MD5Util.encrypt(password);
        if(!user.getPassword().equals(passwordMD5)){
            mv.addObject("message","原密码输入不正确！");
            mv.setViewName("portal/changePassword");
            return mv;
        }else if(!newPassword.equals(checkPassword)){
            mv.addObject("message","新密码与确认密码不一致！");
            mv.setViewName("portal/changePassword");
            return mv;
        }else{
            String newPasswordMD5 = MD5Util.encrypt(newPassword);
            user.setPassword(newPasswordMD5);
            userService.update(user);
            System.out.println("未加密的新密码为"+newPassword+"，加密的新密码为"+newPasswordMD5);
        }
        httpSession.removeAttribute(userName);
        System.out.println("用户名为："+userName);
        redirectAttributes.addFlashAttribute("message","密码修改成功，请重新登录!");
        return new ModelAndView(new RedirectView("/goLogout"));
    }
}
